package cn.blogsx.datasource.druid;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/*
    druid工具类
 */
public class JDBCDruidUtils {
    private static DataSource ds;

    static {
        try {
        Properties pro = new Properties();
        InputStream is = JDBCDruidUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            pro.load(is);
            //获取dataSource
            try {
                ds = DruidDataSourceFactory.createDataSource(pro);
            } catch (Exception e) {
                e.printStackTrace();
            }


        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }

    //释放资源
    public static void close(Connection conn, Statement stmt, ResultSet rs) {
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(stmt!=null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    public static void close(Connection conn, Statement stmt) {
      close(conn,stmt,null);
    }
    //获取连接池
    public static DataSource getDataSource() {
        return ds;
    }
}
